package org.erepublik.company.service;

import java.util.ArrayList;
import java.util.Arrays;

import org.erepublik.company.ECountry;
import org.erepublik.company.Job;
import org.erepublik.company.comparators.JobComparatorByPriceInGold;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class JSONJobService extends JSONProductService<Job> {

    public JSONJobService() {
        super("job");
    }

    @Override
    protected Job[] getEmptyTable() {
        return new Job[0];
    }

    @Override
    protected Job[] getProductFromJSONArray(JSONArray jsonArrayWithFood) throws JSONException {
        Job[] ticket = new Job[jsonArrayWithFood.length()];
        for (int i = 0; i < jsonArrayWithFood.length(); i++) {
            ticket[i] = Job.getJobFromJSON( (JSONObject)jsonArrayWithFood.get(i) );
        }
        Arrays.sort(ticket, new JobComparatorByPriceInGold());
        return ticket;
    }
    

    public Job[] getJobs(ECountry country, int minSkill) {
        update();
        if (country==null)
            return filter( allProducts ,  minSkill );
        return filter( productMap.get(country) ,  minSkill );
    }
    
    private Job[] filter(Job[] jobs, int maxSkill) {
        ArrayList<Job> jobList = new ArrayList<Job>();
        for (Job job : jobs) {
     

            if (job.getMinimalSkill() > maxSkill )
                continue;
            
            jobList.add(job);
        }
        
        return jobList.toArray(new Job[0]);
    }
    

}
